import { useEffect, useRef, useState } from 'react'
import * as echarts from 'echarts'
import { Card, Breadcrumb } from 'antd' 
import { Link } from 'react-router-dom'
import { Col, Row } from 'antd'
import './index.scss'
import labelList from '@/utils/lable'
import { getAllBlogAPI } from '@/api/blog'
import { getBlogByLabelAPI } from '@/api/label'

const Home = () => {
  // 柱状图
  const chartRef1 = useRef(null)
  const chartRef2 = useRef(null)

  // 获取所有博客
  const [blogInfo, setBlogInfo] = useState([])
  // 按月份给博客分组
  const [monthBlogList, setMonthBlogList] = useState([])
  const getMonthBlogList = async (data) => {
    const monthBlogInfo = data.reduce((acc, obj) => {
      const date = new Date(obj.createTime)
      const month = date.getMonth() + 1 // 月份从0开始，所以要加1
      if (!acc[month]) {
        acc[month] = []
      }
      acc[month].push(obj)
      return acc
    }, {})
    setMonthBlogList(monthBlogInfo)
  }

  // 渲染图表
  const renderCharts = () => {
    // 1. 生成实例
    const myChart1 = echarts.init(chartRef1.current)
    const xAxisData = Object.keys(monthBlogList).map(month => `${month} 月`)
    const seriesData = Object.values(monthBlogList).map(arr => arr.length)
    // 2. 准备图表参数
    const option1 = {
      title: {
        text: '每月发布博客数量',
        left: 'center'
      },
      xAxis: {
        type: 'category',
        data: xAxisData
      },
      yAxis: {
        type: 'value'
      },
      grid: {
        height: '70%',
        width: '70%'
      },
      series: [
        {
          data: seriesData,
          type: 'bar'
        }
      ]
    }
    // 3. 渲染参数
    myChart1.setOption(option1)

    // 1. 生成实例
    const myChart2 = echarts.init(chartRef2.current)
    // 2. 准备图表参数
    const option2 = {
      title: {
        text: '博客分类统计',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: pieData.legendData
      },
      series: [
        {
          name: '博客分类',
          type: 'pie',
          radius: '50%',
          data: pieData.seriesData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    // 3. 渲染参数
    myChart2.setOption(option2)
  }

  // 定义一个默认的空数据饼状图
  const [pieDataReady, setPieDataReady] = useState(false)
  const defaultPieData = { legendData: [], seriesData: [] }
  const [pieData, setPieData] = useState(defaultPieData)
  const formatChartData = (data) => {
    const legendData = []
    const seriesData = []

    for (const [label, count] of Object.entries(data)) {
      legendData.push(label)
        seriesData.push({ name: label, value: count })
    }

    return { legendData, seriesData }
  }

  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await getAllBlogAPI()
        const filteredBlogInfo = res.data.filter((item) => item.state !== "草稿")
        setBlogInfo(filteredBlogInfo)
        getMonthBlogList(filteredBlogInfo)  // 在获取博客信息后立即处理数据
      } catch (error) {
        console.error('Error fetching blog info', error)
      }
    }
    fetchData()  // 调用获取和处理博客信息的函数

    // 获取分类
    const getLableInfo = async () => {
      try {
        const counts = {}
        for (const label of labelList) {
          const response = await getBlogByLabelAPI(label.name)
          counts[label.name] = Number(response.data.length) + 1
        }
        const formattedData = formatChartData(counts)
        setPieData(formattedData) // 更新饼状图数据
        setPieDataReady(true)
      } catch (error) {
        console.error('Error fetching label info', error)
        setPieData(defaultPieData) // 如果出现错误，使用默认的空数据
        setPieDataReady(true)
      }
    }

    getLableInfo() // 调用获取分类信息的函数
  }, [])  // 只在组件挂载时获取博客信息

  useEffect(() => {
    if (pieDataReady && Object.keys(monthBlogList).length > 0) {
      renderCharts()  // 确保在 monthBlogList 更新后渲染图表
    }
  }, [pieDataReady, monthBlogList])  // 当 monthBlogList 更新时触发
  
  return (
    <Card
        className='home'
        title={
            <Breadcrumb items={[
            { title: <Link to={'/'}>首页</Link> }
            ]} />
        }
        style={{ marginBottom: 20 }}>
          <Row gutter={16}>
            <Col span={12}>
              <Card title="博客数量" bordered={false}>
                {blogInfo.length}
              </Card>
            </Col>
            <Col span={12}>
              <Card title="标签数量" bordered={false}>
                {labelList.length}
              </Card>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <div ref={chartRef1} style={{ width: '90%', height: '450px' }} />
            </Col>
            <Col span={12}>
              <div ref={chartRef2} style={{ width: '100%', height: '450px' }} />
            </Col>
          </Row>
    </Card>
  )
}

export default Home